package cn.itcast.nems.product.service.impl;

import cn.itcast.nems.common.bean.KeyValue;
import cn.itcast.nems.product.dao.entity.ProductSnapshot;
import cn.itcast.nems.product.dao.mapper.ProductSnapshotMapper;
import cn.itcast.nems.product.dto.ProductSnapshotDTO;
import cn.itcast.nems.product.service.ProductSnapshotService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 产品快照 服务实现类
 * </p>
 *
 * @author liyong
 * @since 2023-08-31
 */
@Service
@AllArgsConstructor
public class ProductSnapshotServiceImpl extends ServiceImpl<ProductSnapshotMapper, ProductSnapshot> implements ProductSnapshotService {
    private final ProductSnapshotMapper productSnapshotMapper;

    @Transactional
    @Override
    public String addProductSnapshot(ProductSnapshotDTO dto, String operator) {
        this.productSnapshotMapper.updateLatestFlag(dto.getProductId(), false);
        ProductSnapshot snapshot = new ProductSnapshot();
        BeanUtils.copyProperties(dto, snapshot);
        snapshot.setLatestFlag(true);
        snapshot.setCreatedBy(operator);
        snapshot.setCreatedDatetime(LocalDateTime.now());
        this.productSnapshotMapper.insert(snapshot);
        return snapshot.getId();
    }

    @Override
    public Map<Long, String> findSnapshotIds(Set<Long> productIds) {
        final List<KeyValue<Long, String>> list = this.productSnapshotMapper.selectSnapshotIds(productIds);
        return list.stream().collect(Collectors.toMap(kv -> kv.getKey(), kv -> kv.getValue()));
    }

    @Override
    public ProductSnapshot getLatestProductSnapshot(@NonNull Long productId) {
        return productSnapshotMapper.selectOne(new LambdaQueryWrapper<ProductSnapshot>()
                .eq(ProductSnapshot::getProductId, productId)
                .eq(ProductSnapshot::getLatestFlag, true)
                .eq(ProductSnapshot::getDeletedFlag, Boolean.FALSE)
                );
    }

    @Override
    public String getLatestProductSnapshotId(@NonNull Long productId) {
        return productSnapshotMapper.selectLatestProductSnapshotId(productId);
    }
}
